package com.sk.weichat.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sk.weichat.AppConstant;
import com.sk.weichat.R;
import com.sk.weichat.Reporter;
import com.sk.weichat.adapter.CommonRecyclerAdapter;
import com.sk.weichat.bean.AttentionUser;
import com.sk.weichat.bean.Friend;
import com.sk.weichat.bean.User;
import com.sk.weichat.bean.message.ChatMessage;
import com.sk.weichat.bean.message.NewFriendMessage;
import com.sk.weichat.bean.message.XmppMessage;
import com.sk.weichat.broadcast.CardcastUiUpdateUtil;
import com.sk.weichat.db.dao.FriendDao;
import com.sk.weichat.db.dao.NewFriendDao;
import com.sk.weichat.db.dao.OnCompleteListener2;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.base.EasyFragment;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.message.ChatActivity;
import com.sk.weichat.ui.message.TabFansEditActivity;
import com.sk.weichat.ui.message.TabFriendActivity;
import com.sk.weichat.util.AsyncUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.util.UiUtils;
import com.sk.weichat.view.XRecyclerView;
import com.sk.weichat.xmpp.ListenerManager;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.ListCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ArrayResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 好友列表
 * create by swy 2019-07-12
 */
public class TabFansFragment extends EasyFragment {

    private SmartRefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private CommonRecyclerAdapter mAdapter;

    public List<User> getmSortFriends() {
        return mSortFriends;
    }

    private List<User> mSortFriends;
    private String mLoginUserId;
    private int page = 0;
    private int pageSize = 50;

    private static final int maxCount = 20;
    private RefreshBroadcastReceiver mRefreshBroadcastReceiver;
    private boolean mIsEdit;//编辑
    private int mSelectedCount = 0;//选中数量
    private int mSystemCount = 0;//系统客服数量

    public static TabFansFragment newInstance(Bundle args) {
        TabFansFragment f = new TabFansFragment();
        f.setArguments(args);
        return f;
    }

    public TabFansFragment() {
        mSortFriends = new ArrayList<>();
    }

    @Override
    protected int inflateLayoutId() {
        return R.layout.fragment_tab_fans;
    }

    @Override
    protected void onActivityCreated(Bundle savedInstanceState, boolean createView) {
        mLoginUserId = coreManager.getSelf().getUserId();
        Bundle bundle = getArguments();
        if (bundle != null) {
            mIsEdit = bundle.getBoolean("isEdit", false);
        }
        initView();
        upDataFriend();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mActivity.unregisterReceiver(mRefreshBroadcastReceiver);

    }

    private void initView() {
        recyclerView = findViewById(R.id.pull_refresh_list);
        LinearLayoutManager manager = new LinearLayoutManager(mActivity);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(manager);
        initListAdapter();
        refreshLayout = findViewById(R.id.refresh_friend_layout);
        refreshLayout.setDragRate(0.4f);//刷新拉动阻尼效果，数值越小，拉动距离越大
        refreshLayout.setEnableOverScrollBounce(false);//禁止越界回弹
        refreshLayout.setEnableLoadMore(false);

        if (mIsEdit) {
            refreshLayout.setEnableRefresh(false);
        }
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 0;
                upDataFriend();
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                upDataFriend();
            }
        });
        mRefreshBroadcastReceiver = new RefreshBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(com.sk.weichat.broadcast.OtherBroadcast.NAME_CHANGE);
        mActivity.registerReceiver(mRefreshBroadcastReceiver, intentFilter);
    }


    private class RefreshBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(com.sk.weichat.broadcast.OtherBroadcast.NAME_CHANGE)) {
                upDataFriend();
            }
        }
    }

    //初始化适配器及事件
    private void initListAdapter() {
        mAdapter = new CommonRecyclerAdapter(R.layout.row_sort_friend, mSortFriends) {
            @Override
            public void convert(BaseViewHolder holder, int position) {

                LinearLayout layout_row_sort = holder.getView(R.id.layout_row_sort);
                ImageView avatar_img = holder.getView(R.id.avatar_img);
                TextView nick_name_tv = holder.getView(R.id.nick_name_tv);
                TextView roles = holder.getView(R.id.roles);
                holder.getView(R.id.catagory_title).setVisibility(View.GONE);
                AttentionUser friend = mSortFriends.get(position).getFriends();

                if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                    avatar_img.setImageResource(R.mipmap.ic_service);
                } else {
                    AvatarHelper.getInstance().displayAvatar(friend.getToUserId(), avatar_img, true);
                }
               /* if (!friend.getUserId().equals(avatar_img.getTag(R.id.avatar_img))) {
                    if (friend.getUserId().equals(Friend.ID_SYSTEM_MESSAGE)) {
                        avatar_img.setImageResource(R.mipmap.ic_service);
                    } else {
                        AvatarHelper.getInstance().displayAvatar(friend.getToUserId(), avatar_img, true);
                    }
                    avatar_img.setTag(R.id.avatar_img, friend.getUserId());
                }*/
                // 昵称
                nick_name_tv.setText(!TextUtils.isEmpty(friend.getRemarkName()) ? friend.getRemarkName() : mSortFriends.get(position).getNickName());
                //好友
                if (friend.getStatus() == Friend.STATUS_FRIEND) {
                    roles.setVisibility(View.VISIBLE);
                    roles.setBackgroundResource(R.drawable.bg_role_friend);
                    roles.setText(getString(R.string.friend));
                } else {
                    roles.setVisibility(View.GONE);
                }

                if (mIsEdit) {//编辑删除状态
                    //头像不可点击
                    avatar_img.setClickable(false);
                    holder.getView(R.id.chat_msc).setVisibility(View.VISIBLE);
                    ((CheckBox) holder.getView(R.id.chat_msc)).setChecked(mSortFriends.get(position).isSelected());
                } else {
                    avatar_img.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(requireActivity(), PersonalCenterActivity.class);
                            intent.putExtra(AppConstant.EXTRA_USER_ID, mSortFriends.get(position).getUserId());
                            requireActivity().startActivity(intent);
                        }
                    });
                }

                //item点击事件监听
                layout_row_sort.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (mIsEdit) {
                            //编辑删除状态
                            if (mSortFriends.get(position).isSelected()) {
                                mSortFriends.get(position).setSelected(false);
                                ((CheckBox) holder.getView(R.id.chat_msc)).setChecked(false);
                                mSelectedCount--;
                                ((TabFansEditActivity) getActivity()).updateRightTitle(mSelectedCount);
                            } else {
                                if (mSelectedCount >= maxCount) {
                                    ToastUtil.showToast(getActivity(), getString(R.string.tips_max_count_remove_fans_one_time));
                                    return;
                                }
                                mSortFriends.get(position).setSelected(true);
                                ((CheckBox) holder.getView(R.id.chat_msc)).setChecked(true);
                                mSelectedCount++;
                                ((TabFansEditActivity) getActivity()).updateRightTitle(mSelectedCount);
                            }

                        } else {
                            AttentionUser attentionUser = mSortFriends.get(position).getFriends();
                            Friend friend = FriendDao.getInstance().getFriend(mLoginUserId, attentionUser.getToUserId());
                            Intent intent = new Intent(requireActivity(), ChatActivity.class);
                            intent.putExtra(ChatActivity.FRIEND, friend);
                            intent.putExtra(Constants.NEW_MSG_NUMBER, friend.getUnReadNum());
                            requireActivity().startActivity(intent);
                        }
                    }
                });

            }
        };

        //禁止RecyclerView的默认动画
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setHasStableIds(true);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onClick(View v) {

    }

    public void refreshData() {
        page = 0;
        if (refreshLayout != null) {
            refreshLayout.resetNoMoreData();
            refreshLayout.setEnableLoadMore(true);
        }
        upDataFriend();
    }

    /**
     * 从服务端获取好友列表，更新数据库
     */
    private void upDataFriend() {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("pageIndex", page + "");
        params.put("pageSize", pageSize + "");
        params.put("status", "5");//好友关系状态：1、关注；2，好友；5，粉丝；如果不传三种关系都查

        HttpUtils.get().url(coreManager.getConfig().FRIENDS_LIST)
                .params(params)
                .build()
                .execute(new ListCallback<User>(User.class) {
                    @Override
                    public void onResponse(ArrayResult<User> result) {
                        if (result.getResultCode() == 1) {
                            if (page == 0) {
                                refreshLayout.finishRefresh();
                                mSortFriends.clear();
                            } else {
                                refreshLayout.finishLoadMore();
                            }
                            if (mIsEdit) {
                                for (int i = 0; i < result.getData().size(); i++) {
                                    if (result.getData().get(i).getFriends().getToUserType() != 2) {//2表示系统账号
                                        mSortFriends.add(result.getData().get(i));
                                    } else {
                                        mSystemCount++;
                                    }
                                }
                                //展示去掉系统客服的粉丝数
                                ((TabFansEditActivity) getActivity()).updateTitle();
                            } else {
                                mSortFriends.addAll(result.getData());
                            }

                            mAdapter.notifyDataSetChanged();

                            if (result.getData().size() == pageSize) {
                                refreshLayout.setEnableLoadMore(true);
                                refreshLayout.setEnableAutoLoadMore(true);
                            } else {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                refreshLayout.setEnableFooterFollowWhenNoMoreData(true);
                            }

                            if (!mIsEdit) {
                                // 本地保存用户列表
                                saveUserList(result);
                            }
                        } else {
                            refreshLayout.finishLoadMoreWithNoMoreData();
                            refreshLayout.setEnableFooterFollowWhenNoMoreData(true);
                            ToastUtil.showToast(mActivity, result.getResultMsg());
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        refreshLayout.finishRefresh();
                        ToastUtil.showErrorNet(getActivity());
                    }
                });
    }

    /**
     * 本地保存用户列表
     *
     * @param result
     */
    private void saveUserList(ArrayResult<User> result) {
        AsyncUtils.doAsync(TabFansFragment.this, e -> {
            Reporter.post("保存好友失败，", e);
            AsyncUtils.runOnUiThread(requireContext(), ctx -> {
                ToastUtil.showToast(ctx, R.string.data_exception);
            });
        }, c -> {

            FriendDao.getInstance().addUserList(coreManager.getSelf().getUserId(), result.getData(),
                    new OnCompleteListener2() {

                        @Override
                        public void onLoading(int progressRate, int sum) {

                        }

                        @Override
                        public void onCompleted() {
                            ((TabFriendActivity) getActivity()).downloadUserInfo();

                        }
                    });

        });
    }

}
